package org.smth.search.indexer.impl;

import com.google.inject.Inject;
import com.google.inject.Singleton;

import org.smth.search.fetcher.impl.RunnableBase;
import org.smth.search.indexer.IndexManager;
import org.smth.search.indexer.Indexer;
import org.smth.search.persistence.DataService;
import org.smth.search.pojos.OnePost;

import java.util.List;
import java.util.concurrent.Callable;

@Singleton
public class IndexManagerImpl extends RunnableBase implements IndexManager, Callable<Object> {

	@Inject
	private Indexer indexer;

	@Inject
	private DataService service;

	private boolean stopOneFinish = false;

	protected Callable<Object> createRunnable() {
		return this;
	}

	public int getLastId() {
		return indexer.getMaxId();
	}

	public void close() {
		this.stop();
		try {
			while (this.isRunning()) {
				Thread.sleep(100);
			}
			indexer.close();
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}

	public Object call() throws Exception {
		while (this.running) {
			int max = indexer.getMaxId();
			List<OnePost> posts = service.getPostsWithIdGT(max, 100);
			if (posts != null && posts.size() > 0) {
				for (OnePost post : posts) {
					if (!running) {
						return indexer.getMaxId();
					}
					indexer.indexPost(post);
				}
			} else {
				if (!running) {
					return indexer.getMaxId();
				} else {
					if (this.isStopOneFinish()) {
						return indexer.getMaxId();
					} else {
						Thread.sleep(5000);
					}
				}
			}
		}
		return indexer.getMaxId();
	}

	public boolean isStopOneFinish() {
		return stopOneFinish;
	}

	public void setStopOneFinish(boolean stopOneFinish) {
		this.stopOneFinish = stopOneFinish;
	}

}
